﻿using System;
using UnityEngine;

namespace Net
{
    public delegate BaseMessage MessageDecodeHandler(byte[] data, int offset, int length);
    /// <summary>
    /// 将二进制解码为消息
    /// </summary>
    public static class MessageDecoder
    {
        public static BaseMessage Decode(byte[] data, ref int offset)
        {
            var msgId = BitConverter.ToInt16(data, 0);
            try
            {
                var message = MessageFactory.Create(msgId);
                if (message == null)
                {
#if UNITY_EDITOR    
                    Debug.LogError($"MessageFactory.Create({msgId}) return null");
#endif
                    return null;
                }
                message.Deserialize(data, ref offset);
                return message;
            }
            catch (Exception e)
            {
#if UNITY_EDITOR
                Debug.LogException(e);    
#endif
            }
            return null;
        }

    }
}